import pygame
try:
	import pygame._view
except:
	pass
import sys
import g
from character import Ken
import net
from util import *
import content
import socket


def ed(data):
	return str(data)

def dd(data):
	return eval(data)

allServers = []

SERVERLISTPORT = 12321

sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.bind( ("", SERVERLISTPORT) )
sock.sendto(ed({"type":"get"}), ("morganquirk.com", SERVERLISTPORT))
(data, addr) = sock.recvfrom(2048)
allServers = dd(data)["data"]
sock.close()

selected = -1

pygame.init()

#pygame.font.init()

screen = pygame.display.set_mode((640, 480))
font = pygame.font.SysFont(None, 22)

selectedServer = None
while selectedServer == None:
	for evt in pygame.event.get():
		if evt.type == pygame.QUIT:
			sys.exit()

		if evt.type == pygame.MOUSEMOTION:
			selected = int((evt.pos[1]) / 20)
			if selected >= len(allServers):
				selected = -1

		if evt.type == pygame.MOUSEBUTTONDOWN:
			if evt.button == 1:
				if selected >= 0 and selected < len(allServers):
					selectedServer = allServers[selected]["ip"]

	screen.fill( (255,255,255) )

	if selected >= 0:
		pygame.draw.rect(screen, (200, 240, 255), (1, selected * 20 + 1, 638, 18), 0)

	y = 0
	for server in allServers:
		surf = font.render(server["name"] + " (" +server["ip"] + ")" , True, (0,0,0))
		screen.blit(surf, (2, y + 2))
		y += 20

	pygame.display.update()
	

pygame.display.quit()
from client import runGame
if len(sys.argv) == 1:
	runGame([selectedServer])
else:
	runGame([selectedServer, sys.argv[1]])
